package com.yonyougov.devops.cruxcisupport.k8s.event;

import com.yonyougov.devops.cruxcisupport.k8s.K8sRepository;
import com.yonyougov.devops.cruxcisupport.k8s.error.K8sConfIgNotFindException;
import io.fabric8.kubernetes.api.model.Event;
import io.fabric8.kubernetes.api.model.EventList;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
public class EventRepositoryImpl implements EventRepository{
    private final K8sRepository k8sRepository;

    public EventRepositoryImpl(K8sRepository k8sRepository) {
        this.k8sRepository = k8sRepository;
    }

    @Override
    public List<Event> getEventsByPodName(String nameSpace, String podName) throws K8sConfIgNotFindException {
        KubernetesClient client = k8sRepository.createDefaultClient(nameSpace);
        return getEventsByPodName(client,nameSpace,podName);
    }

    @Override
    public List<Event> getEventsByPodName(KubernetesClient client, String nameSpace, String podName) {
        EventList eventList = client.events().inNamespace(nameSpace).list();
        if(null == eventList){
            return null;
        }
        return eventList.getItems().stream()
                .filter(event -> event.getMetadata().getName().contains(podName))
                .collect(Collectors.toList());
    }
}
